import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyRefresh extends StatefulWidget {
  final Function() onRefresh;
  final Function() onLoading;
  final Widget child;

  const MyRefresh({Key key, this.onRefresh, this.onLoading, this.child})
      : super(key: key);

  @override
  _MyRefreshState createState() => _MyRefreshState();
}

class _MyRefreshState extends State<MyRefresh> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      onRefresh: () async {
        await widget.onRefresh();
        _refreshController.refreshCompleted();
      },
      onLoading: () async {
        await widget.onLoading();
        _refreshController.loadComplete();
      },
      enablePullDown: true,
      enablePullUp: true,
      header: CustomHeader(builder: (BuildContext context, RefreshStatus mode) {
        Widget body;
        if (mode == RefreshStatus.canRefresh) {
          body = Text("下拉刷新");
        } else if (mode == RefreshStatus.refreshing) {
          body = CupertinoActivityIndicator();
        } else if (mode == RefreshStatus.failed) {
          body = Text("加载失败！点击重试！");
        } else if (mode == RefreshStatus.completed) {
          body = Text("完成");
        } else {
          body = Text("完成");
        }
        return Container(
          height: 55.0,
          child: Center(child: body),
        );
      }),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text("上拉加载");
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("加载失败！点击重试！");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("松手,加载更多!");
          } else {
            body = Text("没有更多数据了!");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      child: widget.child,
    );
  }
}
